<template>
  <div class="popup_wrap" v-if="props.modelValue">
    <Popup :show-close="props.showClose" ref="popup" @close="close" :title="props.title" :icon="props.icon">
      <slot></slot>
    </Popup>
    <div ref="modal" class="modal" @click="modalClose" v-if="props.hasModal && props.modelValue">
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watchEffect, nextTick } from 'vue';
import Popup from './popup.vue';

const props = defineProps({
  hasModal: {
    default() {
      return true
    }
  },
  modelValue: {
    default() {
      return false
    }
  },
  title: String,
  icon: String,
  timing: {
    type: Number,
    default() {
      return 200
    }
  },
  showClose: {
    default() {
      return true
    }
  },
  closeOnClickModal: {
    default() {
      return true
    }
  },
  beforeClose: {
    default() {
      return () => true
    }
  }
})
const emits = defineEmits(['update:modelValue', 'handleActEnd'])
const modal = ref();
const popup = ref();

const modalClose = () => {
  if (!props.closeOnClickModal) return;
  close();
}

const close = () => {
  if (!props.beforeClose())
    return

  if (props.hasModal) {
    opacityOut();
  }
  slideOut();
  setTimeout(() => {
    emits('update:modelValue', false)
    handleActEnd('out')
  }, props.timing)

}

const opacityEnter = async () => {
  modal.value.style.transition = `all ${props.timing / 1000 + 's'} linear`
  await nextTick()
  modal.value.style.opacity = 1
}
const opacityOut = () => {
  modal.value.style.opacity = 0;
}
const slideEnter = async () => {
  popup.value.$el.style.transition = `all ${props.timing / 1000 + 's'} linear`
  await nextTick()
  popup.value.$el.style.top = document.body.clientHeight - popup.value.$el.clientHeight + 'px';
}

const slideOut = async () => {
  popup.value.$el.style.top = '100vh'
}

const handleActEnd = (type) => {
  setTimeout(() => {
    emits('handleActEnd', type)
  }, props.timing)
}

onMounted(() => {
  watchEffect(async () => {
    if (props.modelValue) {
      await nextTick();
      if (props.hasModal) {
        opacityEnter();
      }
      slideEnter();
      handleActEnd('in')
    }
  })

})
</script>

<style lang="scss" scoped>
.popup_wrap {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10000;
}

.modal {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  top: 0;
  left: 0;
  opacity: 0;
  overflow: hidden;
}

.popup {
  top: 100vh;
  position: fixed;
}

.slide-enter-active,
.slide-leave-active,
.fade-enter-active,
.fade-leave-active {
  transition: all .2s linear;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateY(6.93rem);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>